/**
 * @Description Ext.translate for ExtJS 2.x and 3.x; Auto translation with Google Translation API (java/php server side)
 * @author  Tomislav Milkovic
 * @license LGPLv3 http://www.opensource.org/licenses/lgpl-3.0.html
 * @version 1.6, 20.09.2009.
 */


/**
 * @updated 05.08.2009
 * @description ConfigGrid component for editing translations. This is front end suport for server side servlet for managing translations.
 * 
 */
Ext.namespace('Ext.translate');

var textField = new Ext.form.TextField({ allowBlank: false });
var htmleditor = new Ext.form.HtmlEditor({
        xtype: 'htmleditor',
        enableColors: true,
        enableAlignments: true,
        listeners : {
			afterrender : function(){
					var tb = this.getToolbar();
					tb.addSpacer();
					var btn = tb.addButton({text : 'Close' , 
					    handler : function(){
								this.gridEditor.completeEdit(); 
							}, 
					    scope : this
					    ,
					    listeners : {
					    	render : function(){
					    			this.btnEl.dom.className='';
								}
					    	}
						});
					this.setHeight(120);
				}
		}
    }); 
	

Ext.translate.ConfigGrid = Ext.extend(Ext.grid.EditorGridPanel, {

	loadMask : true,
    clicksToEdit: 2,
    languageId : Ext.id(),
    columns : [
               {dataIndex: "key", header: "Default Data", sortable: true,editor: textField},
               {dataIndex: "value", header: "Translated Data",  sortable: true,editor: htmleditor}
               ],
    
    initComponent : function() {

        // typical viewConfig
        this.viewConfig = {
            forceFit: true
        };


        
        this.relayEvents(this.store, ['destroy', 'save', 'update']);        
         
        this.selector = new Ext.translate.LanguageCombo({});
        
        // build toolbars and buttons.
        this.tbar = this.buildTopToolbar();
        
        // super
        Ext.translate.ConfigGrid.superclass.initComponent.call(this);
        
        this.on('render',function(){
            this.buildTopToolbar2();                       
	  		this.loadLanguageList();
        });
        this.on('beforeedit',function(e){
        	return !(('key' == e.field) &&  !e.record.phantom);
        });
        
        this.on('afteredit',function(e){
        	if (!(('key' == e.field) &&  e.record.phantom)) return;
        	e.record.id=e.value;
        });
        
        Ext.translate.Cache.on('aftertranslate', function(){
   	      this.store.setBaseParam( 'language' ,Ext.translate.currentLanguage);
 	      this.store.load({ params : {records:'',language: this.selector.getValue()}});
        },this);
       
        Ext.translate.Cache.on('beforetranslate', function(){
        	//this.loadMask.el.mask();
        	this.loadMask.show();
        },this);
    },
   		    
    loadLanguageList : function(){
  		var fn = function (){
  			  this.eraseCookie("ext-tran-ed");
			  this.selector.store.loadData(Ext.translate.languages);
			  Ext.translate.Manager.generateFlagsCSS(Ext.translate.languages);
			  this.selector.enable();	  	
			  this.selector.setValue(Ext.translate.currentLanguage);			  
  		};	
  		//cookie is sent through AJAX call to notify translation service it is requesting list for editor ,thus enabling 
  		//list of special resource languages to show on language selector
  		this.createCookie("ext-tran-ed", true);
  		Ext.translate.Manager.getSupportedLanguages(fn.createDelegate(this));
    },
    
    buildTopToolbar : function() {
        return [
		{
		    xtype:'splitbutton',
		    text: 'Add...',
		    iconCls: 'silk-add',
		    menu: [{text: 'Add Language', id : Ext.id() + 'addlng', handler: this.onAddLanguage,scope: this },
		           {text: 'Add Resource', id: Ext.id() + 'addres', handler: this.onAddResource,scope: this }
		    		],
		    tooltip : 'Add language or resource'
        }, '-', {
            text: 'Remove...',
            iconCls: 'silk-delete',
            handler: this.onRemoveLanguage,
            scope: this,
            tooltip : 'Remove language or resource'
        }, '-', {
            text: 'Import',
            iconCls: 'icon-arrow-up',
            handler: this.onImport,
            scope: this
        }, '-', {
            xtype:'splitbutton',
            text: 'Export',
            iconCls: 'icon-arrow-down',
            menu: [{text: 'Selected Language', id : Ext.id() + 'expsell', handler: this.onExport},
                   {text: 'All Languages', id: Ext.id() + 'expadd', handler: this.onExport}
            		],
            scope: this
        },
        '-', 
        this.selector
        ];        
    },
    
    buildTopToolbar2 : function() {
    	var owner = this;
 	   var tbar2 = new Ext.Toolbar({
 		      renderTo: this.tbar,
 		      items: [{
 		           text: 'Add',
 		           iconCls: 'silk-add',
 		           handler: this.onAdd,
 		           scope: this,
 		           tooltip : 'Add new translation'
 		       }, '-', {
 		           text: 'Delete',
 		           iconCls: 'silk-delete',
 		           handler: this.onDelete,
 		           scope: this,
 		          tooltip : 'Delete translation'
 		       }, '-', {
 		           text: 'Save',
 		           iconCls: 'icon-save',
 		           handler: this.onSave,
 		           scope: this,
 		          tooltip : 'Save all changes'
 		       }, '-', {
 		           text: 'Reset',
 		           iconCls: 'silk-table-refresh',
 		           handler: this.onReload,
 		           scope: this,
 		          tooltip : 'Reset all changes'
 		       }
//NOT AVAILABLE YET
// 		       ,{text:'Advanced Filter', iconCls:'icon-prefs', tooltip : 'Data filter form', 
//                   handler : function(){
//                	  					var ff = new Ext.ux.GridFormFilter({scope : owner, mode:2 ,url:'advFilter' , baseParams :  {id: 'Ext.translate.ConfigGrid'}});
//                	  					var w = ff.getWin();
//                	  					w.show();
//                	                   }
//                  } 		       
 		       ]
 		      });
 	   
	 },
	 
	 createCookie : function(name,value,days) {
			if (days) {
				var date = new Date();
				date.setTime(date.getTime()+(days*24*60*60*1000));
				var expires = "; expires="+date.toGMTString();
			}
			else var expires = "";

			var this_uri = new URI(location.pathname);
			var req_uri  = new URI(Ext.translate.URL);
			var path_uri = req_uri.resolve(this_uri);
			document.cookie = name+"="+value+expires+"; path="+path_uri;
		},

	 readCookie : function(name) {
			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for(var i=0;i < ca.length;i++) {
				var c = ca[i];
				while (c.charAt(0)==' ') c = c.substring(1,c.length);
				if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
			}
			return null;
		},

	 eraseCookie : function(name) {
			this.createCookie(name,"",-1);
	 },
		
    onImport : function(btn,ev){
		 
    	dialog = new Ext.ux.UploadDialog.Dialog({
    		  id : Ext.id(),
    		  renderTo : Ext.getBody(),
    		  url: Ext.translate.URL,
    		  reset_on_hide: false,
    		  allow_close_on_upload: true,
    		  upload_autostart: true
    		});
    	dialog.on('uploadcomplete',function(){
    		this.eraseCookie('action');
    		this.eraseCookie('cmd');
    	},this);

    	dialog.on('uploadstart',function(){
    		this.createCookie('action',Ext.translate.action[2],0);
    		this.createCookie('cmd','importLang',0);
    	},this);    	
    		dialog.show();
    },
    
    onExport : function(btn,ev){
    	var obj = {action: Ext.translate.action[2], 'cmd' : 'exportLang', 'language' : ''};
    	
    	if(btn.id.search('expsell')>-1)
    		obj.language = Ext.translate.currentLanguage;

    	var url = Ext.urlAppend(Ext.translate.URL, Ext.urlEncode(obj));
    	location.href = url;
    },
    
    infoMsg : function(message, title ){
    	   Ext.Msg.show({
    	      title: title,
    	      msg: message ,
    	      buttons: Ext.MessageBox.OK,
    	      icon: Ext.MessageBox.INFO
    	     });
     },
    
     
     addFn : function(value,text,status){
    	 
    	 Ext.Ajax.request( {
             url : Ext.translate.URL,
             method : 'GET',
             scriptTag : false,
             debug : Ext.translate.debug,
             params : {action: Ext.translate.action[1], cmd : 'add' , proxyGroup : status , language : value},
             success: function(response, request){
                 		var obj = Ext.decode(response.responseText);
                 		if (obj.success==true){
                 			Ext.translate.Manager.setlanguage(value);
                 			this.loadLanguageList(); 
                 			this.infoMsg(text + ' successfully added!','Info');
                 		} else this.infoMsg(obj.msg,'Info');
             		},
             failure: function(response, request){this.infoMsg('Error doing request!' ,'Info');},
             scope : this
         });
    	 
     },
     
     onAddResource : function(btn, ev) {
    	 var obj = this;
         var fn = function(id,value){
             if (id=='ok'){             	
            	 obj.addFn(value, 'Resource', 'TRUE');                 
             }
           };
         Ext.MessageBox.prompt('New Resource','Enter new resource name.', fn,this);    	
     },
     
    onAddLanguage : function(btn, ev) {
    	var obj = this;
        var fn = function(id,value){
            if (id=='ok'){
            	obj.addFn(value, 'Language', 'TRUE');                
            }
          };
        Ext.MessageBox.prompt('New Language','Enter new language name.', fn,this);    	
    },

    onRemoveLanguage : function(btn, ev) {
    	 
        Ext.Ajax.request( {
            url : Ext.translate.URL,
            method : 'GET',
            scriptTag : false,
            debug : Ext.translate.debug,
            params : {action: Ext.translate.action[1], cmd : 'remove' , language : this.selector.getValue()},
            success: function(response, request){
		        		var obj = Ext.decode(response.responseText);
		        		if (obj.success==true){
		        			Ext.translate.Manager.setlanguage(Ext.translate.defaultLanguage);
		        			this.loadLanguageList(); 
		        			this.onReload();
		        			this.infoMsg('Language successfully removed!','Info');
		        		} else this.infoMsg(obj.msg,'Info');            	
            		},
            failure: function(result, request){this.infoMsg('Error doing request!' ,'Info');},
            scope : this
        });
        
    },
    
    onReload : function(btn,ev){
    	this.store.load();
    },
    
    onSave : function(btn, ev) {
        this.store.save();
    },

    onAdd : function(btn, ev) {
        var Record = this.store.recordType;
        var u = new Record({
            key: '',
            value: ''
        });
    	
        this.stopEditing();
        this.store.insert(0, u);
        this.startEditing(0, 1);
    },

    onDelete : function(btn, ev) {
        var index = this.getSelectionModel().getSelectedCell();
        if (!index) {
            return false;
        }
        var rec = this.store.getAt(index[0]);
        this.store.remove(rec);
    }
});
